package com.pactera.madp.cp.controller.oms.contact;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pactera.madp.common.core.exception.CheckedException;
import com.pactera.madp.common.core.util.R;
import com.pactera.madp.common.log.annotation.SysLog;
import com.pactera.madp.cp.api.dto.contact.ContactPageDTO;
import com.pactera.madp.cp.api.dto.contact.SyncContactDetailsTendencyDTO;
import com.pactera.madp.cp.api.dto.contact.UpdateContactDto;
import com.pactera.madp.cp.api.em.contactfield.AddWayEnum;
import com.pactera.madp.cp.api.em.permission.ReqPerEnum;
import com.pactera.madp.cp.api.entity.WorkContactEntity;
import com.pactera.madp.cp.api.model.workcontact.ContactData;
import com.pactera.madp.cp.api.model.workcontact.GetContactInfoResponse;
import com.pactera.madp.cp.api.model.workcontact.GetContactRequest;
import com.pactera.madp.cp.api.vo.contact.*;
import com.pactera.madp.cp.handler.CorpContextHolder;
import com.pactera.madp.cp.service.IContactService;
import com.pactera.madp.cp.service.impl.AccountService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.jsoup.internal.StringUtil;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @description: 客户管理
 * @author: zhaojinjian
 * @create: 2020-11-26 14:56
 **/
@RestController
@AllArgsConstructor
@RequestMapping("/workcontact")
@Api(value = "workcontact", tags = "客户管理")
public class ContactController {

    private IContactService contactService;

    /**
     * 获取客户列表
     * @param page
     * @param parem
     * @param permission
     * @return
     */
    @GetMapping("/page")
    @ApiOperation(value = "获取客户列表")
    public R<Page<List<ContactData>>> index(Page page, GetContactRequest parem, ReqPerEnum permission) {
        verifyParam(parem);
        Integer corpId = CorpContextHolder.getCorpId();
        Integer empId = AccountService.getEmpId();
        if (corpId != null && empId != null) {
            return R.ok(contactService.getContactPage(page, parem, empId, corpId, permission));
        }
        return R.ok();
    }

    /**
     * @description 查看客户详情基本信息
     * @author zhaojinjian
     * @createTime 2020/12/2 15:45
     */
    @GetMapping("/show")
    @ApiOperation(value = "查看客户详情基本信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name="contactId",value="客户id",dataType = "Integer"),
            @ApiImplicitParam(name="employeeId",value="员工id",dataType = "Integer")
    })
    public R<GetContactInfoResponse> showContactInfo(Integer contactId, Integer employeeId) {
        Integer corpId = CorpContextHolder.getCorpId();
        return R.ok(contactService.getContactInfo(contactId, employeeId, corpId));
    }

    /**
     * @author: yangpengwei
     * @time: 2021/2/19 4:53 下午
     * @description 客户详情接口
     */
    @GetMapping("/{wxExternalUserid}")
    @ApiOperation(value = "查看客户详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name="wxExternalUserid",value="客户微信 id")
    })
    public R<ContactDetailVO> contactDetail(@PathVariable String wxExternalUserid) {
        if (wxExternalUserid == null || wxExternalUserid.isEmpty()) {
            return R.failed("客户微信 id 不能为空");
        }
        return R.ok(contactService.getContactDetailByWxExternalUserId(wxExternalUserid));
    }

    /**
     * @author: yangpengwei
     * @time: 2021/2/19 4:53 下午
     * @description 客户互动轨迹
     */
    @GetMapping("/track")
    @ApiOperation(value = "客户互动轨迹")
    @ApiImplicitParams({
            @ApiImplicitParam(name="contactId",value="客户id",dataType="Integer")
    })
    public R<Page<List<ContactTrackVO>>> contactTrack(Integer contactId, Page page,Integer employeeId) {
        if (contactId == null) {
            return  R.failed("客户 id 不能为空");
        }
        return R.ok(contactService.getContactTrackByContactId(contactId,page,employeeId));
    }

    /**
     * @description 修改客户详情基本信息
     * @author zhaojinjian
     * @createTime 2020/12/11 16:18
     */
    @SysLog("修改客户详情基本信息")
    @PutMapping
    @ApiOperation(value = "修改客户详情基本信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name="employeeId",value="员工id",dataType="Integer")
    })
    public R updateContact(@RequestBody UpdateContactDto parem,@RequestParam Integer employeeId) {
//        Map<String, Integer> corpIdAndEmpIdMap = AccountService.getCorpIdAndEmpIdMap();
//        Integer corpId = corpIdAndEmpIdMap.get("corpId");
//        Integer empId = corpIdAndEmpIdMap.get("empId");
        WorkContactEntity contactEntity = contactService.getById(parem.getContactId());
        if (contactEntity == null) {
            return R.failed(Boolean.FALSE,"该客户不存在");
        }
        Integer corpId = contactEntity.getCorpId();
        return contactService.updateContact(parem, corpId, employeeId) ? R.ok(Boolean.TRUE,"修改成功") : R.failed(Boolean.FALSE,"修改失败") ;
    }

    /**
     * @description 同步客户
     * @author zhaojinjian
     * @createTime 2020/12/11 16:18
     */
    @SysLog("同步客户")
    @PutMapping("/syncontact")
    @ApiOperation(value = "同步客户")
    public R<Boolean> synContact() {
        Integer corpId = CorpContextHolder.getCorpId();
        if (corpId == null) {
            return R.failed();
        }
        return contactService.synContact(corpId) ? R.ok(Boolean.TRUE,"同步成功") : R.failed(Boolean.FALSE,"同步失败") ;
    }

    /**
     * @description 客户来源下拉框
     * @author zhaojinjian
     * @createTime 2020/12/11 16:37
     */
    @GetMapping("/source")
    @ApiOperation(value = "客户来源下拉框")
    public R<List<ContactSourceVo>> source() {
        List<ContactSourceVo> sourceVos = new LinkedList<>();
        for (AddWayEnum addWayEnum : AddWayEnum.values()) {
            ContactSourceVo sourceVo = new ContactSourceVo();
            //暂时屏蔽 手机通讯录、来自微信的添加好友申请、管理员/负责人分配、自动拉群等来源
            if (addWayEnum.getCode().equals("202") || addWayEnum.getCode().equals("1002") || addWayEnum.getCode().equals("7") || addWayEnum.getCode().equals("5")){
                continue;
            }
            sourceVo.setAddWay(addWayEnum.getCode());
            sourceVo.setAddWayText(addWayEnum.getMsg());
            sourceVos.add(sourceVo);
        }
        return R.ok(sourceVos);
    }

    @GetMapping("/losscontact")
    @ApiOperation(value = "流失提醒")
    @ApiImplicitParams({
            @ApiImplicitParam(name="employeeId",value="员工id",dataType="String"),
            @ApiImplicitParam(name="page",value="条数",dataType="Integer"),
            @ApiImplicitParam(name="perPage",value="页数",dataType="Integer")
    })
    public R<Page<List<ContactLossVO>>> getLossContact(String employeeId, Page page) {
        if (employeeId == null || StringUtil.isBlank(employeeId)) {
            return R.failed("员工id不能为空");
        }
        Integer corpId = CorpContextHolder.getCorpId();
        String[] empIdArray = employeeId.split(",");
        List<Integer> empIds = new ArrayList<>();
        for (int i = 0; i < empIdArray.length; i++) {
            empIds.add(Integer.parseInt(empIdArray[i]));
        }
        return R.ok(contactService.getlossContact(corpId, empIds,page));
    }

    /**
     * 参数校验
     * @param param
     */
    private void verifyParam(GetContactRequest param) {
        if (param.getFieldId() != null && !param.getFieldId().equals("0") && param.getFieldType().isEmpty()) {
            throw new CheckedException("非法的参数");
        }
        if (param.getFieldType() != null && !param.getFieldType().equals("0") && param.getFieldValue().isEmpty()) {
            throw new CheckedException("非法的参数");
        }
        if ("全部".equals(param.getAddWay())) {
            param.setAddWay("");
        }
        if(StrUtil.isNotBlank(param.getKeyWords()) && param.getKeyWords().length() > 20) {
            throw new CheckedException("非法参数， 关键词最长20个字符！");
        }
    }

    /**
     * 获取客户信息分页列表-新需求
     * @param page
     * @param dto
     * @return
     */
    @GetMapping("/new/page")
    @ApiOperation(value = "客户信息列表-新")
    public R<Page<ContactPageVO>> getPageList(Page page,ContactPageDTO dto){
        if(StrUtil.isNotBlank(dto.getName()) && dto.getName().length() > 20) {
            return R.failed("非法参数， 客户姓名最长20个字符！");
        }
        return R.ok(contactService.getPageList(page,dto));
    }

    /**
     * 获取客户详情-新需求
     * @param id
     * @return
     */
    @GetMapping("/new/{id}")
    @ApiOperation(value = "获取客户基础信息-新")
    @ApiImplicitParams({
            @ApiImplicitParam(name="id",value="客户id",dataType = "Integer",paramType = "path"),
            @ApiImplicitParam(name="custNo",value="crm系统客户编号",dataType = "String")
    })
    public R<ContactNewDetailsVO> getContactDetails(@PathVariable Integer id,@RequestParam(name = "custNo",required = false) String custNo){
        return R.ok(contactService.getContactDetails(id,custNo));
    }

    /**
     * 根据客户id获取员工与客户信息列表
     * @param page
     * @param id
     * @return
     */
    @GetMapping("/new/page-employee")
    @ApiOperation(value = "根据客户id获取员工与客户信息列表")
    public R<Page<EmployeeListByContactVO>> getEmployeeListByContact(Page page,@RequestParam Integer id){
        return R.ok(contactService.getEmployeeListByContact(page,id));
    }

    /**
     * 根据客户id修改客户编号
     * @param workContactEntity
     * @return
     */
    @SysLog("根据客户id修改客户编号")
    @PutMapping("/new/update-contact-num")
    @ApiOperation(value = "根据客户id修改客户编号")
    public R updateContactNum(@RequestBody WorkContactEntity workContactEntity){
        return contactService.updateById(workContactEntity) ? R.ok(Boolean.TRUE,"修改成功") : R.failed(Boolean.FALSE,"修改失败");
    }

    @GetMapping("/statistics")
    @ApiOperation(value = "华融湘江客户同步统计基础信息")
    public R<SyncContactStatisticsVO> getStatisticsData(){
        return R.ok(contactService.getStatisticsData());
    }


    @GetMapping("/tendency")
    @ApiOperation(value = "华融湘江客户同步统计趋势图")
    public R<List<SyncContactStatisticsTendencyVO>> getContactDetailsTendency(SyncContactDetailsTendencyDTO dto){
        Integer type = dto.getType();
        switch (type) {
            case 1:
                return R.ok(contactService.getContactTotalCount(dto));
            case 2:
                return R.ok(contactService.getCrmContactCount(dto));
            case 3:
                return R.ok(contactService.getNonBankContactCount(dto));
            case 4:
                return R.ok(contactService.getWxContactCount(dto));
            case 5:
                return R.ok(contactService.getQywxContactCount(dto));
        }
        return R.failed("查询字段类型不在1-5内");
    }

}
